module sw.upload.uploadlist;

version(Upload):

import nazo.savedata;

alias TSaveData!("upload.lst") UploadList;


import std.stdio, std.regexp, nazo.file, std.date, nazo.serialize;

struct UploadItem{
  string filename;
  ubyte[/*16*/] filemd5;
  uint time;
  uint size;
  string name;
  ubyte[/*16*/] md5;
}

///新しいUploadList
struct NewUploadList{
  invariant string path = "newupload.lst";
  void append(UploadItem* item){
    ubyte[] data = serialize(*item);
    .append(path, data ~ serialize(data.length)); // 長さを先に入れるべき? あと*itemじゃなくitemでできるようにするべき。
  }
  d_time lastModified(){
    return getLastWriteTime(path);
  }
  UploadItem[] getList(){
    ubyte[] file = cast(ubyte[])read(path);
    UploadItem[] rv;
    ubyte* ptr = file.ptr;
    for(;ptr < file.ptr + file.length;){
      UploadItem tmp;
      deserialize!(UploadItem)(ptr, tmp);
      ptr += 4;
      rv ~= tmp;
    }
    return rv;
  }
  int opApply(int delegate(ref UploadItem) dg){
    ubyte[] file = cast(ubyte[])read(path);
    int rv;
    ubyte* ptr = file.ptr;
    for(;ptr < file.ptr + file.length;){
      UploadItem tmp;
      deserialize!(UploadItem)(ptr, tmp);
      ptr += 4;
      rv = dg(tmp);
      if(rv) break;
    }
    return rv;
  }
  int opApplyReverse(int delegate(ref UploadItem) dg){
    ubyte[] file = cast(ubyte[])read(path);
    int rv;
    ubyte* ptr = file.ptr + file.length - 4;
    for(;ptr >= file.ptr;){
      ubyte* tptr = ptr -= *cast(size_t*)ptr;
      UploadItem tmp;
      deserialize!(UploadItem)(tptr, tmp);
      ptr -= 4;
      rv = dg(tmp);
      if(rv) break;
    }
    return rv;
  }
}


/+
unittest{
  NewUploadList uploadList;
  auto a = UploadItem("test1", [0,1,2,3], 12, 12, "test", [4,5,6,7]);
  uploadList.append(&a);
  a = UploadItem("test2", [0,1,2,3], 12, 12, "test", [4,5,6,7]);
  uploadList.append(&a);
  a = UploadItem("test3", [0,1,2,3], 12, 12, "test", [4,5,6,7]);
  uploadList.append(&a);
  foreach(UploadItem i;uploadList.getList)
    writefln(i.tupleof);
  foreach(UploadItem i;uploadList)
    writefln(i.tupleof);
  foreach_reverse(UploadItem i;uploadList)
    writefln(i.tupleof);
}
+/
